<?php
/**
 * @copyright: ©2024 永州 微聚商网络科技有限公司
 * @link: https://www.wEijuyunke.com
 */

namespace app\mobile\controller;

use app\admin\model\FigureDistribution;
use app\admin\model\FigureMember;
use app\admin\model\FigureMemberLog;
use app\admin\model\FigureResourcesProfit;
use app\admin\model\FigureShareholderLog;
use app\BaseController;
use think\App;
use think\facade\Request;
use think\facade\Db;
use think\facade\Log;
use think\Model;
use app\admin\model\FigureUser;
use app\admin\model\FigureSystem;
use app\admin\model\FigureBrokerageLog;
use app\admin\model\FigureBrokerageSet;
use app\admin\model\FigureCommission;
use app\admin\model\FigureBrokerage;
use app\admin\model\template\WithdrawApply;
use app\admin\model\FigurePromotionSet;
use app\admin\model\FigureBalanceLog;

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true'); // 是否允许后续请求携带认证信息（cookies）,该值只能是true,否则不返回
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); // 允许的请求类型
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
// 允许的请求头字段

/**
 * 分销操作
 *
 * @author Administrator
 *
 */
class Brokerage extends BaseController
{

    /**
     * 分销设置
     * http://aigc.weijuyunke.cn/mobile/brokerage/set
     */
    public function set()
    {
        $set = FigureBrokerageSet::where("id", 1)->find();
        if (empty($set)) {
            $set = [];
        }

        if (!empty($set['explain'])) {
            $set['explain'] = htmlspecialchars_decode($set['explain']);
        }
        $set['self_purchase_member_name'] = '';
        $set['member_money'] = '';
        if ( $set['self_purchase_swich'] == 1){
          $FigureMember =   new FigureMember();
            $FigureMemberInfo = $FigureMember->where(['id' => $set['self_purchase_member_id']])->find();
            if ($FigureMemberInfo){
                $set['self_purchase_member_name'] = $FigureMemberInfo['name'];
                $set['member_money'] = $FigureMemberInfo['money'];
            }else{
                $set['self_purchase_member_name'] = '未设置';
            }
        }


        return result(0, 'success', $set);
    }

    /**
     * 分销首页
     * http://aigc.weijuyunke.cn/mobile/brokerage/index
     *
     * @param
     *            uid 用户id
     */
    public function index()
    {
        $uid = input('uid');
        $user = FigureUser::where('id', $uid)->find();

        if (empty($user)) {
            return result(-1, '未找到用户');
        }

        $setting = FigureBrokerageSet::where('id', 1)->find();
        if ($setting['self_purchase_swich'] == 1){
            $memberLog = new FigureMemberLog();
            $twoUserBuyCount = $memberLog->where(['uid' =>$uid, 'pay_status'=> 2,'member_id' => $setting['self_purchase_member_id']])->count();
            if ($user['distribution_level']  == 1 && $twoUserBuyCount == 0){
                $user['level_name'] = '';
            }else{
                $FigureDistributionModel = new FigureDistribution();
                $FigureDistributionInfo = $FigureDistributionModel->where(['id' => $user['distribution_level_id']])->find();
                if (isset($FigureDistributionInfo['name'])) {
                    $user['level_name'] =$FigureDistributionInfo['name'];
                } else {
                    $user['level_name'] = '分销等级不存在';
                }
            }
        }else{
            $FigureDistributionModel = new FigureDistribution();
            $FigureDistributionInfo = $FigureDistributionModel->where(['id' => $user['distribution_level_id']])->find();
            if (isset($FigureDistributionInfo['name'])) {
                $user['level_name'] =$FigureDistributionInfo['name'];
            } else {
                $user['level_name'] = '分销等级不存在';
            }
        }
        $result = [];
        $date = date('Y-m-d', time());
        $teamCount = FigureUser::where("pid = {$uid} OR pid in (select id from wjyk_figure_user where pid = {$uid})")->count();
        $todayCount = FigureUser::where("  DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m-%d') = '{$date}' AND (pid = {$uid} OR pid in (select id from wjyk_figure_user where pid = {$uid}))")->count();
        $monthCount = FigureUser::where("  DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m') = '{$date}' AND  (pid = {$uid} OR pid in (select id from wjyk_figure_user where pid = {$uid}))")->count();


        $user['teamCount'] = empty($teamCount) ? 0 : $teamCount;
        $user['todayCount'] = empty($todayCount) ? 0 : $todayCount;
        $user['monthCount'] = empty($monthCount) ? 0 : $monthCount;

        $year = date('Y', time());
        $month = date('Y-m', time());

        $allGet = FigureBrokerageLog::where(" pid = {$uid} ")->sum('money');
        $yearGet = FigureBrokerageLog::where(" pid = {$uid}  AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y') = '{$year}' ")->sum('money');
        $monthGet = FigureBrokerageLog::where(" pid = {$uid}  AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m') = '{$month}' ")->sum('money');
        $todayGet = FigureBrokerageLog::where("  pid = {$uid}  AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m-%d') = '{$date}' ")->sum('money');

        $figureResourcesProfit = new FigureResourcesProfit();
        $allGetProfit = $figureResourcesProfit->where(" uid = {$uid} ")->sum('user_profit');
        $yearGetProfit = $figureResourcesProfit->where(" uid = {$uid}  AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y') = '{$year}' ")->sum('user_profit');
        $monthGetProfit = $figureResourcesProfit->where(" uid = {$uid}  AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m') = '{$month}' ")->sum('user_profit');
        $todayGetProfit = $figureResourcesProfit->where("  uid = {$uid}  AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m-%d') = '{$date}' ")->sum('user_profit');


        $user['allCommisson'] = empty($allGet) ? 0 : round($allGet, 2);
        $user['yearCommisson'] = empty($yearGet) ? 0 : round($yearGet);
        $user['monthCommisson'] = empty($monthGet) ? 0 : round($monthGet);
        $user['todayCommisson'] = empty($todayGet) ? 0 : round($todayGet);

        $user['allProfit'] = empty($allGetProfit) ? 0 : round($allGetProfit, 2);
        $user['yearProfit'] = empty($yearGetProfit) ? 0 : round($yearGetProfit);
        $user['monthProfit'] = empty($monthGetProfit) ? 0 : round($monthGetProfit);
        $user['todayProfit'] = empty($todayGetProfit) ? 0 : round($todayGetProfit);

        $user['allGet'] = bcadd($allGet, $allGetProfit, 2); //empty($allGet) ? 0 : round($allGet, 2);
        $user['yearGet'] = bcadd($yearGet, $yearGetProfit, 2);;
        $user['monthGet'] = bcadd($monthGet, $monthGetProfit, 2);;
        $user['todayGet'] = bcadd($todayGet, $todayGetProfit, 2);;

        $p_nickname = '平台';
        if (!empty($user['pid'])) {
            $pUser = FigureUser::where('id', $user['pid'])->find();
            $p_nickname = empty($pUser['nickname']) ? '' : $pUser['nickname'];
        }
        $user['p_nickname'] = $p_nickname;

        return result(0, 'success', $user);
    }

    /**
     * 分销统计
     * http://aigc.weijuyunke.cn/mobile/brokerage/statis
     *
     * @param
     *            uid 用户id
     */
    public function statis()
    {
        $uid = input('uid');
        $user = FigureUser::where('id', $uid)->find();

        if (empty($user)) {
            return result(-1, '未找到用户');
        }

        $result['brokerage'] = $user['brokerage'];

        $date = date('Y-m-d', time());
        $already = FigureBrokerage::where(" uid = {$uid} ")->sum('commission_wait');
        $today = FigureBrokerage::where(" uid = {$uid} AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m-%d') = '{$date}' ")->sum('commission_wait');

        //  $figureResourcesProfit = new FigureResourcesProfit();
        //  $figureResourcesProfitAlready  = $figureResourcesProfit->where(" uid = {$uid} ")->sum('user_profit');
        //   $figureResourcesProfitToday  = $figureResourcesProfit->where(" uid = {$uid} AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m-%d') = '{$date}' ")->sum('user_profit');;


        $result['alreadyCommission'] = $already; ///bcadd($already,$figureResourcesProfitAlready,2) ;
        $result['todayCommission'] = $today;// bcadd($today,$figureResourcesProfitToday,2) ;

        $yesterday = date("Y-m-d", strtotime("-1 day"));
        $yesterdayGet = FigureBrokerageLog::where(" pid = {$uid} AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m-%d') = '{$yesterday}' ")->sum('money');


        $result['yesterdayGet'] = $yesterdayGet;

        return result(0, 'success', $result);
    }

    /**
     * 提现申请
     * https://aigc.weijuyunke.cn/mobile/brokerage/cashwait
     *
     * @param
     *            uid 用户id
     * @param
     *            commission_wait 申请金额
     * @param
     *            cash_type 1-线下提现，2-线上提现
     * @param
     *            telphone 电话
     * @param
     *            nickname 昵称
     */
    public function cashwait()
    {
        Db::startTrans();
        try {
            $payData = '';
            $request = $this->request;
            $user_id = $this->request->_UID;

            $uid = input('uid');

            $commission_wait = input('commission_wait');

            $operater = FigureUser::where('id', $uid)->find();

            if (empty($operater)) {
                return result(-1, '未找到用户');
            }

            if ($commission_wait <= 0) {
                return result(-1, '申请金额错误');
                exit();
            }

            if ($commission_wait > $operater['brokerage']) {
                return result(-1, '佣金不足');
                exit();
            }

            $set = FigureBrokerageSet::where("id", 1)->find();

            if ($commission_wait < $set['cash_limit']) {
                return result(-1, '申请金额不足每次最低提现');
                exit();
            }

            if ($commission_wait > $set['cash_highest']) {
                return result(-1, '申请金额超过每次最高提现');
                exit();
            }

            $data = array(
                'uid' => $uid,
                'log_no' => getPayNo('TX'),
                'cash_type' => input('cash_type'),
                'commission_wait' => $commission_wait,
                'pay_type' => 0,
                'is_status' => 1
            );

            if (!empty(input('telphone'))) {
                $data['telphone'] = input('telphone');
            }

            if (!empty(input('nickname'))) {
                $data['nickname'] = input('nickname');
            }

            if (!empty($set['cash_charge'])) {
                $data['cash_charge'] = $set['cash_charge'];
                if (!empty($set['service_charge'])) {
                    $data['service_ratio'] = $set['service_charge'];
                    $data['service_charge'] = round($commission_wait * $set['service_charge'] * 0.01, 2);
                } else {
                    $data['service_ratio'] = 0;
                    $data['service_charge'] = 0;
                }
                $data['commission_actual'] = round($commission_wait * $set['cash_charge'], 2);
            } else {
                $data['cash_charge'] = 0;
                if (!empty($set['service_charge'])) {
                    $data['service_ratio'] = $set['service_charge'];
                    $data['service_charge'] = round($commission_wait * $set['service_charge'] * 0.01, 2);
                    $data['commission_actual'] = $commission_wait - $data['service_charge'];
                } else {
                    $data['service_ratio'] = 0;
                    $data['service_charge'] = 0;
                    $data['commission_actual'] = $commission_wait;
                }
            }
            $log = new FigureBrokerage();
            $payconfig = sysconfig('pay');
            if (input('cash_type') == 2 && $payconfig['pay_type'] == 1 && $payconfig['wx_transfer_version'] == 2 && $payconfig['pay_remit_type'] == 2) {
                $payData = [];
                $res = json_decode(sendMoney($data['log_no'], $data['commission_actual'], $operater['openid']), true);
                if ($res['code'] != 1) {
                    Db::rollback();
                    return result(-1, '打款异常:' . $res['msg']);
                }
                if ($payconfig['pay_type'] == 1) {
                    $payData = [
                        'pay_mchid' => $payconfig['pay_mchid'],
                        'pay_appid' => $payconfig['pay_appid'],
                    ];
                } else {
                    $payData = [
                        'pay_mchid' => $payconfig ['pay_service_mchid'],
                        'pay_appid' => $payconfig ['pay_service_appid'],
                    ];
                }
                $payData['package_info'] = $res['data']['package_info'];
                $data['wx_transfer_version'] = 2;

            }
            $result = $log->save($data);
            if ($result) {
                FigureUser::where('id', $uid)->save([
                    'brokerage' => Db::raw('brokerage-' . $commission_wait)
                ]);
                $withdrawApply = new WithdrawApply(array(
                    'openid' => $operater['openid'],
                    'name' => $operater['nickname'],
                    'money' => $commission_wait,
                    'service' => round($data['service_charge'], 2),
                    'account' => $data['cash_type'] == 1 ? $data['nickname'] : $operater['nickname'],
                    'time' => date('Y-m-d H:i', time())
                ));
                $withdrawApply->send();
                Db::commit();
                return result(0, '申请成功', $payData);
            } else {
                Db::rollback();
                return result(-1, '申请失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 提现记录
     * https://aigc.weijuyunke.cn/mobile/brokerage/commissionLog
     *
     * @param
     *            uid 用户id
     * @param
     *            is_status 1-待审核，2-已打款，3-已驳回
     * @param
     *            page 页码
     * @param
     *            psize 每页条数
     */
    public function commissionLog()
    {
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));

        $uid = input('uid');
        $where = " uid = {$uid} ";

        if (!empty(input('is_status'))) {
            $is_status = input('is_status');
            $where .= "AND is_status = {$is_status}";
        }

        $total = FigureBrokerage::where($where)->count();
        if ($total) {

            $list = FigureBrokerage::where($where)->order('create_time', 'desc')
                ->limit(($pindex - 1) * $psize, $psize)
                ->select();
        } else {
            $list = array();
        }

        $totalPage = ceil($total / $psize);

        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    /**
     * 分销记录
     * http://aigc.weijuyunke.cn/mobile/brokerage/logList
     *
     * @param
     *            uid
     * @param
     *            year 年
     * @param
     *            month 月
     * @param
     *            page 页码
     * @param
     *            psize 每页条数
     */
    public function logList()
    {
        try {
            $uid = session('uid');
            if (empty($uid)) {
                $uid = input('uid');
            }

            $pindex = max(1, intval(input('page')));
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));

            $where = " a.pid = {$uid}";

            if (!empty(input('year'))) {
                $where .= " AND DATE_FORMAT(FROM_UNIXTIME(a.create_time),'%Y') = " . input('year');

                if (!empty(input('month'))) {
                    $where .= " AND DATE_FORMAT(FROM_UNIXTIME(a.create_time),'%m') = " . input('month');
                }
            }

            if (!empty(input('day'))) {
                $day = input('day');
                $where .= " AND DATE_FORMAT(FROM_UNIXTIME(a.create_time),'%Y-%m-%d') = '{$day}'";
            }

            $total = FigureBrokerageLog::alias('a')->leftJoin('wjyk_figure_user b', 'a.uid=b.id')
                ->where($where)
                ->count();
            if ($total) {
                $list = FigureBrokerageLog::alias('a')->leftJoin('wjyk_figure_user b', 'a.uid=b.id')
                    ->where($where)
                    ->field('a.*,b.nickname,b.avatar')
                    ->order('a.create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();
            } else {
                $list = array();
            }

            $totalPage = ceil($total / $psize);

            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 我的团队
     * http://aigc.weijuyunke.cn/mobile/brokerage/teamList
     *
     * @param
     *            uid
     * @param
     *            type 1-一级 2-二级
     * @param
     *            nickname 昵称
     * @param
     *            day 日期
     * @param
     *            page 页码
     * @param
     *            psize 每页条数
     */
    public function teamList()
    {
        $uid = session('uid');
        if (empty($uid)) {
            $uid = input('uid');
        }

        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));

        if (input('type') == 1) {
            $where = " pid = {$uid}";
        } elseif (input('type') == 2) {
            $where = " pid in (select id from wjyk_figure_user where pid = {$uid}) ";
        }

        if (!empty(input('nickname'))) {
            $nickname = input('nickname');
            $where .= " AND nickname LIKE  '%{$nickname}%'";
        }

        if (!empty(input('year'))) {
            $where .= " AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y') = " . input('year');

            if (!empty(input('month'))) {
                $where .= " AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%m') = " . input('month');
            }
        }

        if (!empty(input('day'))) {
            $day = input('day');
            $where .= " AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m-%d') = '{$day}'";
        }

        $total = FigureUser::where($where)->count();
        if ($total) {
            $list = FigureUser::where($where)->order('create_time', 'desc')
                ->limit(($pindex - 1) * $psize, $psize)
                ->select();
            $FigureDistribution  = new FigureDistribution();
            $setting = FigureBrokerageSet::where('id', 1)->find();
            $memberLog = new FigureMemberLog();
            foreach ($list as $k => $v) {
                $money = FigureBrokerageLog::where("pid = {$uid}  AND  uid = {$v['id']} ")->sum('money');
                $list[$k]['money'] = number_format($money, 2);
                if ($setting['self_purchase_swich'] == 1){
                    $twoUserBuyCount = $memberLog->where(['uid' => $v['id'], 'member_id' => $setting['self_purchase_member_id']])->count();
                    if ($v['distribution_level'] == 1 && $twoUserBuyCount==0 ){
                        $list[$k]['distribution_level_name'] = '';
                    }else{
                        $FigureDistributionInfo =  $FigureDistribution->where(['id' =>$v['distribution_level_id'] ])->find();
                        if ($FigureDistributionInfo){
                            $list[$k]['distribution_level_name'] = $FigureDistributionInfo['name'];
                        }else{
                            $list[$k]['distribution_level_name'] = '';
                        }
                    }
                }else{
                    $FigureDistributionInfo =  $FigureDistribution->where(['id' =>$v['distribution_level_id'] ])->find();
                    if ($FigureDistributionInfo){
                        $list[$k]['distribution_level_name'] = $FigureDistributionInfo['name'];
                    }else{
                        $list[$k]['distribution_level_name'] = '';
                    }
                }
            }
        } else {
            $list = array();
        }

        $totalPage = ceil($total / $psize);

        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    public function resourcesProfitList()
    {
        $request = $this->request;
        $param = $request->param();
        try {
            /*$where[] = ['fa.delete_time', '=', null];
            $where[] = ['fca.delete_time', '=', null];
            $where[] = ['fat.delete_time', '=', null];*/
            $order = 'frf.create_time';
            if (!empty($param['uid'])) {
                $where[] = ['frf.uid', '=', $param['uid']];
            }
            if (isset($param['type']) && !empty($param['type'])) {
                if ($param['type'] == 1) {
                    $where[] = ['frf.type', '=', $param['type']];
                } elseif ($param['type'] == 2) {
                    $where[] = ['frf.type', '=', $param['type']];
                } elseif ($param['type'] == 3) {
                    $where[] = ['frf.type', '=', $param['type']];
                } elseif ($param['type'] == 4) { // 标准形象和高级形象
                    $where[] = ['frf.type', 'in', [1, 2]];
                }

            }

            if (!empty($param['order_field'])) {
                $order = $param['order_field'];
            }
            if (!empty(input('year'))) {
                $time = input('year') . '-01-01';
                $endTime = strtotime(input('year') . '-12-31');
                if (!empty(input('month'))) {
                    $time = input('year') . '-' . input('month') . '-01';
                    $endTime = strtotime("+1 month", strtotime($time));;
                }

                $where[] = ['frf.create_time', '>', strtotime($time)];
                $where[] = ['frf.create_time', '<', $endTime];

            }
            $pindex = max(1, intval(input('page')));
            $psize = empty($param['psize']) ? 10 : intval($param['psize']);
            $figureResourcesProfit = new FigureResourcesProfit();
            $total = $figureResourcesProfit->alias("frf")
                ->leftJoin("figure_resources_goods frg", "frf.figure_resources_goods_id = frg.id")
                ->leftJoin("figure_resources_order fro", "frf.order_id = fro.id")
                ->leftJoin("figure_user fu", "frf.uid = fu.id")
                ->leftJoin("figure_avatar fa", "frf.figure_avatar_id = fa.id")
                ->leftJoin("figure_composite_avatar fca", "frf.composite_figure_avatar_id = fca.id")
                ->leftJoin("figure_voice_twin fat", "frf.figure_voice_twin_id = fat.id")
                ->where($where)->count();

            if ($total) {
                $list = $figureResourcesProfit->alias("frf")
                    ->leftJoin("figure_resources_order fro", "frf.order_id = fro.id")
                    ->leftJoin("figure_resources_goods frg", "frf.figure_resources_goods_id = frg.id")
                    ->leftJoin("figure_user fu", "frf.uid = fu.id")
                    ->leftJoin("figure_avatar fa", "frf.figure_avatar_id = fa.id")
                    ->leftJoin("figure_composite_avatar fca", "frf.composite_figure_avatar_id = fca.id")
                    ->leftJoin("figure_voice_twin fat", "frf.figure_voice_twin_id = fat.id")
                    ->field('frf.*,
                    fu.id as fu_id,fu.avatar as fu_avatar,fu.nickname as fu_nickname,
                      fro.log_no as fro_log_no,
                          frg.title as frg_title,
                    fa.id as fa_id,fa.name as fa_name,fa.type as  fa_type,fa.video_url as fa_video_url , fa.video_cover  as fa_video_cover,fa.image_url as fa_image_url ,fa.video_backgroud_image as fa_video_backgroud_image ,fa.video_backgroud_color as fa_video_backgroud_color ,    
                    fca.id as fca_id,fca.name as fca_name,fca.url as fca_url,
                    fat.id as fat_id, fat.name as fat_name,fat.voice_urls as fat_voice_urls,fat.train_mode as fat_train_mode,fat.media_url as fat_media_url')
                    ->where($where)
                    ->order($order, 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();
            } else {
                $list = array();
            }
            $totalPage = ceil($total / $psize);
            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
        }
    }

    public function shareholderLog()
    {
        $uid = input('uid');
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $whereAmount =[];
        $where =[];
        $where[] = [
            "uid",
            "=",
            $uid
        ];

        if (! empty(input('year')) &&  ! empty(input('month')) ) {
            $year = input('year'); // 年份
            $month = input('month'); // 月份
            $firstDayOfMonth = new \DateTime("$year-$month-01 00:00:00");
            $timestampFirstDay = $firstDayOfMonth->getTimestamp();
            $lastDayOfMonth = new \DateTime("$year-$month-01");
            $lastDayOfMonth->modify('last day of this month');
            $timestampLastDay = $lastDayOfMonth->getTimestamp();
            $where[] = [
                "amount_time",
                ">=",
                $timestampFirstDay
            ];
            $where[] = [
                "amount_time",
                "<=",
                $timestampLastDay
            ];
            $whereAmount [] = [
                "amount_time",
                ">=",
                $timestampFirstDay
            ];
            $whereAmount [] = [
                "amount_time",
                "<=",
                $timestampLastDay
            ];
        }else{
            $monthtime = strtotime(date('Y-m-01'));
            $whereAmount [] = [
                "amount_time",
                ">=",
                $monthtime
            ];
        }
        $total = FigureShareholderLog::where(['uid' => $uid])->count();
        $list = FigureShareholderLog::where(['uid' => $uid])
            ->order('create_time', 'desc')
            ->limit(($pindex - 1) * $psize, $psize)
            ->select();

        foreach ($list as $key => $value) {
            $list[$key]['amount_data'] = date('Y-m-d', $value['amount_time']);
            $list[$key]['create_data'] = date('Y-m-d', strtotime($value['create_time']));
        }


        $monthTotalMoney = FigureShareholderLog::where($whereAmount)->sum('money'); // 总分红
        $monthMyMoney = FigureShareholderLog::where(['uid' => $uid])->where($whereAmount)->sum('money'); // 总分红

        $totalPage = ceil($total / $psize);

        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
            ,'month_total_money' => $monthTotalMoney,
            'month_my_money' => $monthMyMoney

        ));

    }


    public function shareholderStatistics()
    {
        $uid = input('uid');
        $totalMoney = FigureShareholderLog::where(['uid' => $uid])->sum('money'); // 总分红
        $now = time();
        $todayMidnight = strtotime('today', $now);
        $totalShareholderLog = FigureShareholderLog::where('create_time', '>=', $todayMidnight)
            ->where(['uid' => $uid])->find();
        $totalTurnover = FigureShareholderLog::sum('money');

        $data['total_money'] = $totalMoney;// 累计分红
        $data['yesterday_total'] = isset($totalShareholderLog['total']) ? $totalShareholderLog['total'] : '0.00';
        $data['yesterday_money'] = isset($totalShareholderLog['money']) ? $totalShareholderLog['money'] : '0.00';
        $data['platform_money'] = $totalTurnover;


        return result(0, 'success', $data);
    }

    public function distributionLevel()
    {
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $figureDistributionModel = new FigureDistribution();
        $total = $figureDistributionModel
            ->count();
        $list = $figureDistributionModel
            ->limit(($pindex - 1) * $psize, $psize)
            ->select();
        $set = FigureBrokerageSet::where("id", 1)->find();
        if ($set['distribution_mode'] == 2) {
            $packageModel = new FigureMember();
        }
        foreach ($list as $key => $value) {
            if ($set['distribution_mode'] == 2) {
                $packageArray = json_decode($value['package_josn'], true);
                if ( $packageArray['package_id']){
                    $packageInfo = $packageModel->where(['id' => $packageArray['package_id']])->find();
                    $list[$key]['package_count'] = $packageArray['package_count'];
                    $list[$key]['package_name'] = $packageInfo['name'];
                    $list[$key]['package_id'] = $packageArray['package_id'];
                }else{
                    $list[$key]['package_count'] = 0;
                    $list[$key]['package_name'] = '未设置';
                    $list[$key]['package_id'] = 0;
                }

            }
            $list[$key]['distribution_mode'] = $set['distribution_mode'];
        }
        $totalPage = ceil($total / $psize);

        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }


}